<?php


namespace app\admin\service;


use app\admin\model\Account;
use app\admin\model\Sign;
use Driver\Cache\Redis;
use Page\Find;
use Page\Page;

class SignService
{
    # 获取所有的sign
    public function getDataSign($name, $page, $limit)
    {
        $user_id = $this->get_user_id($name);
        $result = $this->get_user_id_sign($user_id , $page, $limit);
        return $result;
    }
    # 根据name和sign获取对应的记录
    public function getAllSignData($name, $sign, $model_str, $page, $limit)
    {
        $result = $this->get_all_sign_data($name, $sign, $model_str, $page, $limit);
        return $result;
    }

    # 获取name和sign获取对应的记录并进行layui分页
    private function get_all_sign_data($name, $sign, $model_str, $page, $limit)
    {
        $where =  [
            ['from', '=', $name],
            ['sign', '=', $sign]
        ];
        $classModel = 'app\\admin\\model\\'.$model_str;
        $model = new $classModel;
        $page = new Page($model, $page, $limit, [], null, $where);
        $result = $page->layuiPage();
        return $result;
    }

    # 根基name获取id
    private function get_user_id($name)
    {
        $redis_hash_key = config('redis.account').$name;
        $user_id = Redis::hget($redis_hash_key, 'id');
        if($user_id == false){
            $info = Account::get_id($name);
            return $info['id'];
        }
        return $user_id;
    }

    # 根据user_id获取对应的所有sign
    private function get_user_id_sign($user_id, $page, $limit)
    {
        $model = new Sign();
        $where = [
            ['user_id', '=', $user_id]
        ];
        $page = new Page($model, $page, $limit, [], null, $where);
        $result = $page->layuiPage();
        return $result;
    }

    public function find_data($param)
    {
        $where = $this->get_where($param);
        $param['field']['user_id'] = $this->get_user_id($param['field']['name']);
        unset($param['field']['name']);
        $find = new Find();
        $model = new Sign();
        $result = $find->find($model, $param, $where);
        return $result;
    }

    # 根据参数组装条件
    private function get_where($param)
    {
        $field = $param['field'];
        $user_id = $this->get_user_id($field['name']);
        $where = [
            'status' => ['status', '=', $field['status']],
            'sign' => ['sign', '=', $field['sign']],
            'user_id' => ['user_id', '=', $user_id]
        ];
        return $where;
    }

    #
    private function get_all_param($param)
    {
        $all_param = [];
        foreach ($param['field'] as $key=>$value){
            array_push($all_param, $key);
        }
        return $all_param;
    }

}